<template>
  <div class="hazardous-vehicle-tracking bg-background text-foreground p-4">
    <h2 class="mb-6 text-2xl font-bold">危化品车辆实时定位</h2>

    <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-md">
      <!-- <div class="flex flex-wrap gap-4">
        <div class="flex-1">
          <label for="routeCode" class="block text-sm font-medium">定位终端编码：</label>
          <input id="routeCode" v-model="filters.locate_code" type="text" placeholder="请输入" class="input" />
        </div>
        <div class="flex-1">
          <label for="plateNumber" class="block text-sm font-medium">车牌号码：</label>
          <input id="plateNumber" v-model="filters.license_number" type="text" placeholder="请输入" class="input" />
        </div>
       
        <div class="flex items-end space-x-2">
          <button @click="loadData" class="btn btn-primary">查询</button>
          <button @click="resetFilters" class="btn btn-secondary">重置</button>
        </div>
      </div> -->
      <query-form :model="filters" :formItems="formItems" @search="loadData" @reset="resetFilters" />
    </div>

    <div class="mb-4 space-x-2">
      <!-- <button @click="addNew" class="btn btn-primary">新增</button>
        <button @click="deleteSelected" class="btn btn-destructive">删除</button>
        <button @click="importData" class="btn btn-secondary">导入</button> -->
      <!-- <button @click="exportData" class="btn btn-secondary">导出</button> -->
      <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
    </div>

    <div class="data-table bg-card text-card-foreground overflow-hidden rounded-lg shadow-md">
      <!-- <div class="overflow-x-auto">
        <table class="divide-border min-w-full divide-y">
          <thead>
            <tr class="bg-muted">
              <th class="table-header w-[60px]">
                <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" class="checkbox" />
              </th>
              <th v-for="header in tableHeaders" :key="header" class="table-header">
                {{ header }}
              </th>
              <th class="table-header">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in paginatedData" :key="item.id" class="hover:bg-muted/50">
              <td class="table-cell w-[60px]">
                <input type="checkbox" v-model="item.selected" class="checkbox" />
              </td>
              <td class="table-cell">{{ startIndex + index + 1 }}</td>
              <td class="table-cell">{{ item.locate_code }}</td>
              <td class="table-cell">{{ item.license_number }}</td>
              <td class="table-cell">{{ item.location_description }}</td>
              <td class="table-cell">{{ item.longitude }}</td>
              <td class="table-cell">{{ item.latitude }}</td>
              <td class="table-cell">{{ formatDateTime(item.datetime) }}</td>
              <td class="table-cell">
                <button @click="editItem(item)" class="btn btn-sm btn-secondary">编辑</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div> -->
      <el-table v-loading="loading" :data="paginatedData" style="width: 100%" ref="tableRef" align="center"
        class="data-table" :header-cell-style="headerCellStyle" empty-text="暂无数据">
        <!-- <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column> -->
        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ startIndex + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="LOCATE_CODE" label="定位终端编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LICENSE_NUMBER" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LOCATION_DESCRIPT" label="位置描述" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LONGITUDE" label="经度" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LATITUDE" label="纬度" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DATETIME" label="日期" header-align="center" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.DATETIME) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination bg-card text-card-foreground mt-4 flex items-center justify-between p-4">
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" @close="closeDialog"
      class="bg-background text-foreground">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="定位终端编码" prop="routeCode">
          <el-input v-model="formData.routeCode" class="input"></el-input>
        </el-form-item>
        <el-form-item label="车牌号码" prop="plateNumber">
          <el-input v-model="formData.plateNumber" class="input"></el-input>
        </el-form-item>
        <el-form-item label="位置描述" prop="location">
          <el-input v-model="formData.location" class="input"></el-input>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="formData.longitude" class="input"></el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="formData.latitude" class="input"></el-input>
        </el-form-item>
        <el-form-item label="定位时间" prop="positionTime">
          <el-input v-model="formData.positionTime" type="datetime-local" class="input"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" class="btn btn-secondary">取 消</el-button>
          <el-button type="primary" @click="saveVehicle" class="btn btn-primary">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()
import {
  ElMessage,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
} from 'element-plus'

const apiBaseUrl = ref(proxy.$currentUrl + '/api/hazardous_vehicles')

const filters = ref({
  LOCATE_CODE: '',
  LICENSE_NUMBER: '',
})

const tableHeaders = [
  '序号',
  '定位终端编码',
  '车牌号码',
  '位置描述',
  '经度',
  '纬度',
  '定位时间',
  // '操作',
]

const vehicleData = ref([])
const currentPage = ref(1)
const itemsPerPage = ref(10)
const selectAll = ref(false)
const isEditing = ref(false)
const formData = ref({
  id: null,
  vehicleNumber: '',
  driverName: '',
  contactNumber: '',
  currentLocation: '',
  status: '',
  lastUpdateTime: '',
})

const totalItems = computed(() => vehicleData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / itemsPerPage.value))
const startIndex = computed(() => (currentPage.value - 1) * itemsPerPage.value)


const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value
  const end = start + itemsPerPage.value
  return vehicleData.value.slice(start, end)
})

const displayedPages = computed(() => {
  const range = 2
  const pages = []
  for (
    let i = Math.max(1, currentPage.value - range);
    i <= Math.min(totalPages.value, currentPage.value + range);
    i++
  ) {
    pages.push(i)
  }
  return pages
})

const loadData = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: filters.value,
    })
    vehicleData.value = response.data
    currentPage.value = 1
    loading.value = false
  } catch (error) {
    console.error('获取危化品车辆跟踪失败:', error)
    alert(
      '获取危化品车辆跟踪失败: ' + (error.response?.data?.message || error.message),
    )
  }

}

// const search = () => {
//   // 实现搜索逻辑
//   const { vehicleNumber, driverName } = filters.value
//   vehicleData.value = vehicleData.value.filter(
//     (item) =>
//       (!vehicleNumber || item.vehicleNumber.includes(vehicleNumber)) &&
//       (!driverName || item.driverName.includes(driverName)),
//   )
// }

const resetFilters = () => {
  filters.value = {
    LOCATE_CODE: '',
    LICENSE_NUMBER: '',
  }
  loadData() // 重新加载所有数据
}

const rules = reactive({
  vehicleNumber: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { min: 7, max: 8, message: '车牌号长度应为7-8个字符', trigger: 'blur' },
  ],
  driverName: [{ required: true, message: '请输入司机姓名', trigger: 'blur' }],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  currentLocation: [
    { required: true, message: '请输入当前位置', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
})

const formRef = ref(null)
const dialogVisible = ref(false)
const dialogTitle = computed(() =>
  isEditing.value ? '编辑车辆信息' : '新增车辆信息',
)

const addNew = () => {
  isEditing.value = false
  dialogVisible.value = true
  formData.value = {
    id: null,
    vehicleNumber: '',
    driverName: '',
    contactNumber: '',
    currentLocation: '',
    status: '待出发',
    lastUpdateTime: new Date().toLocaleString(),
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const editItem = (item) => {
  isEditing.value = true
  dialogVisible.value = true
  formData.value = { ...item }
}

const viewItem = (item) => {
  isEditing.value = false
  dialogVisible.value = true
  formData.value = { ...item }
}

const saveVehicle = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        if (isEditing.value) {
          const index = vehicleData.value.findIndex(
            (item) => item.id === formData.value.id,
          )
          if (index !== -1) {
            vehicleData.value[index] = {
              ...formData.value,
              lastUpdateTime: new Date().toLocaleString(),
            }
          }
        } else {
          vehicleData.value.push({
            id: vehicleData.value.length + 1,
            ...formData.value,
            lastUpdateTime: new Date().toLocaleString(),
            selected: false,
          })
        }
        ElMessage.success(isEditing.value ? '编辑成功' : '新增成功')
        closeDialog()
      } else {
        ElMessage.error('请填写完整信息')
        return false
      }
    })
  }
}

const closeDialog = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const deleteSelected = () => {
  vehicleData.value = vehicleData.value.filter((item) => !item.selected)
  selectAll.value = false
}

const removeItem = (item) => {
  vehicleData.value = vehicleData.value.filter((i) => i.id !== item.id)
}

const exportData = () => {
  // const dataToExport = vehicleData.value.map(
  //   ({ id, selected, ...rest }) => rest,
  // )
  const dataToExport = vehicleData.value.map((expert) => ({
    '定位终端编码': expert.LOCATE_CODE,
    '车牌号码': expert.LICENSE_NUMBER,
    '位置描述': expert.LOCATION_DESCRIPT,
    '经度': expert.LONGITUDE,
    '纬度': expert.LATITUDE,
    '日期': formatDateTime(expert.DATETIME),
  }))
  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '危化品车辆实时定位')
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const data = new Blob([excelBuffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  })
  saveAs(data, '危化品车辆实时定位.xlsx')
}

const importData = (event) => {
  const file = event.target.files[0]
  const reader = new FileReader()
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const worksheet = workbook.Sheets[workbook.SheetNames[0]]
    const jsonData = XLSX.utils.sheet_to_json(worksheet)
    vehicleData.value = jsonData.map((item, index) => ({
      id: index + 1,
      ...item,
      selected: false,
    }))
  }
  reader.readAsArrayBuffer(file)
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  vehicleData.value.forEach((item) => (item.selected = selectAll.value))
}

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

const goToPage = (page) => {
  currentPage.value = page
}
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
const formItems = ref([
  {
    label: '定位终端编码：',
    model: 'LOCATE_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '车牌号码：',
    model: 'LICENSE_NUMBER',
    type: 'input',
    placeholder: '请输入',
  },
]);
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
const isDialogType = ref('')
const loading = ref(false)
// Initial data load
onMounted(() => {
  loadData()
})

// 添加这些样式相关的计算属性
const btnClasses = computed(() => {
  return 'px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out'
})

const btnPrimaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-primary text-primary-foreground hover:bg-primary/90',
  ]
})

const btnSecondaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-secondary text-secondary-foreground hover:bg-secondary/80',
  ]
})

const btnDestructiveClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-destructive text-destructive-foreground hover:bg-destructive/90',
  ]
})

// 更新你的模板以使用这些计算属性作为按钮类
</script>

<style scoped>
.input {
  @apply border-input bg-background focus:border-primary focus:ring-primary mt-1 block w-full rounded-md shadow-sm focus:ring focus:ring-opacity-50;
}

.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.checkbox {
  @apply text-primary focus:ring-primary border-input h-4 w-4 rounded;
}

.table-header {
  @apply px-6 py-3 text-left text-xs font-medium uppercase tracking-wider;
}

.table-cell {
  @apply whitespace-nowrap px-6 py-4 text-sm;
}

.btn-pagination {
  @apply border-border relative inline-flex items-center border px-4 py-2 text-sm font-medium;
}

/* 覆盖 Element Plus 的一些样式以匹配我们的主题 */
:deep(.el-dialog) {
  @apply bg-background text-foreground;
}

:deep(.el-dialog__header) {
  @apply bg-muted text-foreground;
}

:deep(.el-dialog__body) {
  @apply bg-background text-foreground;
}

:deep(.el-dialog__footer) {
  @apply bg-muted text-foreground;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}
</style>
